#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024/12/26 16:28
# @Author : ZhengQL

import dmPython
from common.Yaml_Handler import YamlHandler
from common.Path_Handler import PathHandler

class DB_Handler:
    """连接达梦数据库"""

    def __init__(self, server, port, user, password, **kwargs):

        # self.conn = dmPython.connect(host=host, port=port, user=user, password=password,database=database,charset=charset)
        self.conn = dmPython.connect(
            server=server,
            port=port,
            user=user,
            password=password,
            **kwargs
        )

        self.cursor = self.conn.cursor()

    def query(self, sql, args=None, one=True):
        """执行sql语句"""
        self.cursor.execute(sql, args)
        # 提交事务
        self.conn.commit()
        if one:
            return self.cursor.fetchone()
        else:
            return self.cursor.fetchall()

    def close(self):
        """关闭数据库连接"""
        self.cursor.close()
        self.conn.close()


if __name__ == '__main__':
    # 从config.yaml获取链接信息
    server = YamlHandler(PathHandler.config_path + r'/config.yaml').read_yaml()['DM8']['server']
    port = YamlHandler(PathHandler.config_path + r'/config.yaml').read_yaml()['DM8']['port']
    user = YamlHandler(PathHandler.config_path + r'/config.yaml').read_yaml()['DM8']['user']
    password = YamlHandler(PathHandler.config_path + r'/config.yaml').read_yaml()['DM8']['password']

    try:
        conn = DB_Handler(
            server=server,
            port=port,
            user=user,
            password=password,

        )
        # 获取sql语句
        sql = ''.join(YamlHandler(PathHandler.config_path + r'/config.yaml').read_yaml()['sql'])
        print(type(sql), sql)
        datas = conn.query(sql, one=False)
        for data in datas:
            print(data)
    except Exception as e:
        print(e)
    finally:
        conn.close()
